/*
 * Package il.ac.biu.cs.grossmm.impl.activeData
 * File MemPublicationPoint.java
 * 
 * This is a part of presence service framework prototype. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.impl.activeData;

import il.ac.biu.cs.grossmm.api.data.Node;
import il.ac.biu.cs.grossmm.api.data.NodeType;
import il.ac.biu.cs.grossmm.api.data.Root;
import il.ac.biu.cs.grossmm.api.flow.*;
import il.ac.biu.cs.grossmm.api.keys.Key;
import il.ac.biu.cs.grossmm.api.keys.KeyPattern;
import il.ac.biu.cs.grossmm.impl.keys.PatternMatcher;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MemPublicationPoint<N> extends PublicationPointBase<N>
	implements NotificationProvider<N>
	{

	final ConcurrentHashMap<Key, MemRootNode<N>> nodeMap = new ConcurrentHashMap<Key, MemRootNode<N>>();

	static final NodeEventInspector eventInspector = new MemEventInspector();

	/**
	 * All subscrptions to this point. This is essentially a subset of a
	 * dataLayer.subscriptions
	 */
	Map<Key, SubscriptionImpl<N>> subscriptions;

	final DataLayer<N> dataLayer;

	static MemNodeManpipulator memNodeManpipulator = new MemNodeManpipulator();

	public MemPublicationPoint(DataLayer<N> dataLayer, KeyPattern pattern,
			NodeType<N> nodeType, String identifier) {
		super(dataLayer.nodeType, pattern, identifier);

		this.dataLayer = dataLayer;
		this.subscriptions = new HashMap<Key, SubscriptionImpl<N>>();
	}

	public Root<N> createNode(Key key, boolean mayExist)
			throws NodeExistsException {
		MemRootNode<N> n = new LinkedRootNode<N>(nodeType, key);
		// MemRootNode<N> n = new HashedRootNode<N>(nodeType, key);

		MemRootNode<N> oldN = nodeMap.putIfAbsent(key, n);

		if (oldN == null) {
			SubscriptionImpl<N> subscription = subscriptions.get(key);
			// Subscription<N> subscription = dataLayer.lockSubscription(key);

			if (subscription != null) {
				subscription.activate(n);
				// dataLayer.unlockSubscription(subscription);
			}

			return n;
		} else {
			if (!mayExist)
				throw new NodeExistsException(key.toString());
			return oldN;
		}
	}

	public NodeManipulator writeLock(Node node) {
		// TODO lock

		return memNodeManpipulator;
	}

	public void writeUnlock(Node node) {
		MemRootNode<N> n = ((MemRootNode<N>) node.getRoot());

		SubscriptionImpl<N> sub = n.getSubscription();

		n.shift();
		n.makeVisible();

		if (sub == null)
			return;

		sub.nodeUpdated(eventInspector);

		// TODO unlock
	}

	public Node<N> fetch(Key key) {
		MemRootNode<N> n = nodeMap.get(key);
		return n;
	}

	public Root<N> getRoot(Key key) {
		MemRootNode<N> n = nodeMap.get(key);
		return n;
	}

	public NodeInspector readLock(Node<N> node) {
		// TODO Lock
		return dataLayer.adm.memNewInspector;
	}

	public void readUnlock(Node<N> node) {
		// TODO unlock
	}

	public synchronized SubscriptionImpl<N> subscribe(Subscriber<N> subscriber,
			Key key, Track track) {
		MemRootNode<N> root = nodeMap.get(key);

		assert !dataLayer.subscriptions.containsKey(key);

		SubscriptionImpl<N> subscription;

		if (root == null) {
			assert root.getSubscription() == null;
			subscription = new SubscriptionImpl<N>(key, null, this);
			subscription.deactivate(Status.NORESOURCE);
		} else {
			subscription = new SubscriptionImpl<N>(key, root, this);
		}

		SubscriptionImpl<N> s = dataLayer.registerSubscription(key, subscription,
				subscriber);

		if (subscription == s) {
			subscriptions.put(key, subscription);
			Status status = subscription.getStatus();
			if (status == Status.ACTIVE)
				subscriber.activated(key, root);
			else
				try {
					subscriber.deactivated(key, status);
				} catch (NoSuchSubscription e) {
					e.printStackTrace();
				}
		}

		return s;
	}

	public void unsubscribe(Key key) {
		MemRootNode<N> root = nodeMap.get(key);

		if (root != null)
			root.setSubscription(null);

		subscriptions.remove(key);
	}

	public NodeType getNodeType() {
		return nodeType;
	}

	public KeyPattern getPattern() {
		return pattern;
	}

	public void deleteNode(Key key) {
		MemRootNode<N> rootNode = nodeMap.get(key);
		rootNode.remove();
		nodeMap.remove(key);
	}

	public Enumeration<Key> getKeys() {
		return Collections.enumeration(subscriptions.keySet());
	}

	public Enumeration<Key> getKeys(KeyPattern pattern) {
		// TODO Implement getKeys
		// return null;
		throw new RuntimeException("Not implemented");
	}

	public final boolean isPersistent() {
		return false;
	}

	@Override
	public String toString() {
		return "MEM-PP(" + dataLayer.nodeType + ") " + names + " " + pattern
				+ " ";
	}

	public void subscriptionClosed(Subscription<N> subscription) {
		dataLayer.subscriptionClosed(subscription);
	}
}
